package com.iflyings.android.convention

import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import org.gradle.api.Project
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.Delete
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.get
import java.text.SimpleDateFormat
import java.util.*

internal fun Project.createCopyApkTask(extension: AndroidComponentsExtension<*, *, *>) {
    val apkDir = "${project.projectDir}/../apk"
    tasks.register("deleteApk", Delete::class.java) {
        //group = "user"
        dependsOn("assembleRelease")
        setDelete(fileTree(apkDir) {
            include("**/*.apk")
        })
    }
    tasks.register("copyApk", Copy::class.java) {
        group = "user"
        dependsOn("deleteApk")
        from("${project.buildDir}/outputs/apk/release")
        into(apkDir)
        include("*.apk")
    }

    extension.onVariants {
        if (it.name == "release") {
            tasks.findByName("assemble")?.finalizedBy("copyApk")
        }
    }
}

private fun releaseTime(): String {
    return SimpleDateFormat("yyyyMMdd").format(Date())
}

internal fun Project.createCopyJarTask(extension: AndroidComponentsExtension<*, *, *>) {
    val jarDir = "${project.projectDir}/../apk"
    tasks.register("deleteJar", Delete::class.java) {
        //group = "user"
        dependsOn("assembleRelease")
        setDelete(fileTree(jarDir) {
            include("**/*.jar")
        })
    }
    tasks.register("copyJar", Jar::class.java) {
        group = "user"
        dependsOn("deleteJar")
        from("${project.buildDir}/intermediates/runtime_library_classes_dir/release")
        from(fileTree("${project.projectDir}/src/main") {
            include("assets/**")
        })
        destinationDir = file(jarDir)
        archiveName = "mb7-${releaseTime()}.jar"
    }

    extension.onVariants {
        if (it.name == "release") {
            tasks.findByName("assemble")?.finalizedBy("copyJar")
        }
    }
}